const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const Messages = require("./db");
const app = express();
const server = http.createServer(app);

const io = new Server(server, {
  // 允许ws跨域
  cors: {
    origin: "*",
  },
});

app.get("/getMessages", async (req, res) => {
  const messages = await Messages.find({}, { __v: 0 });
  res.json({
    code: 200,
    message: "",
    success: true,
    data: messages,
  });
});

// ws服务器绑定事件，监听客户端连接事件
io.on("connection", (socket) => {
  // 1. 接受客户端发送过来的消息
  socket.on("receive_message", async (data) => {
    // data 发送过来的消息 { username, content, time }
    // 2. 将消息存储在数据库中
    await Messages.create(data);
    // 3. 将消息转发其他人
    socket.broadcast.emit("send_message", data);
  });
});

server.listen(3000, () => {
  console.log("服务器启动成功");
});
